/*jslint browser: true*/
/*global $, jQuery, alert, window*/

function fetchSub() {
    "use strict";
    return {
        "id": window.view.sub_id(),
        "body": window.view.sub_body(),
        "image_id": window.view.sub_image_id(),
        "options": window.view.sub_options(),
        "options_count": window.view.sub_options_count(),
        "analysis": window.view.sub_analysis(),
        "answer": window.view.sub_answer()
    };
}

function fetchHat() {
    "use strict";
    return {
        "id": window.view.hat_id(),
        "hat_body": window.view.hat_body(),
        "hat_image_id": window.view.hat_image_id()
    };
}

window.view = {
    "hat_id": function (id_value) {
        "use strict";
        if (id_value || id_value === "") {
            $("#hat_id").val(id_value);
        } else {
            return parseInt($("#hat_id").val(), 10) || 0;
        }
    },
    "hat_body": function (value_str) {
        "use strict";
        if (value_str || value_str === "") {
            $("#hat_body").val(value_str);
        }
        return window.trim($("#hat_body").val());
        
    },
    "hat_image_id": function (id_value) {
        "use strict";
        if (id_value) {
            $("#hat_upload_image").attr("href", "/link/" + id_value + "/image/")
                    .attr("name", id_value)
                    .html("图片链接,点击可查看");
            $("#hat_upload_loading").hide();
            $("#hat_upload_control").hide();
            $("#hat_upload_result").show();
        } else {
            return parseInt($("#hat_upload_image").attr("name"), 10) || 0;
        }
    },
    "sub_list": function (id_value) {
        "use strict";
        if (id_value) {
            $("#sub_list_select option[value=" + id_value + "]")[0].selected = true;
        }
        return parseInt($("#sub_list_select").val(), 10);
    },
    "sub_id": function (value_str) {
        "use strict";
        if (value_str || value_str === "") {
            $("#sub_id").val(value_str);
        }
        return parseInt($("#sub_id").val(), 10) || 0;
    },
    "sub_body": function (value_str) {
        "use strict";
        if (value_str || value_str === "") {
            $("#q_body").val(value_str);
        }
        return window.trim($("#q_body").val());
    },
    "sub_image_id": function (id_value) {
        "use strict";
        if (id_value) {
            $("#upload_image").attr("href", "/link/" + id_value + "/image/")
                    .attr("name", id_value)
                    .html("图片链接,点击可查看");
            $("#upload_loading").hide();
            $("#upload_control").hide();
            $("#upload_result").show();
        } else {
            return parseInt($("#upload_image").attr("name"), 10) || 0;
        }
    },
    "sub_options": function (value_str) {
        "use strict";
        if (value_str || value_str === "") {
            $("#q_options").val(value_str);
        }
        return window.trim($("#q_options").val());
    },
    "sub_options_count": function (count_num) {
        "use strict";
        if (count_num) {
            $("#options_count option[value=" + count_num + "]")[0].selected = true;
        }
        return parseInt($("#options_count").val(), 10);
    },
    "sub_analysis": function (value_str) {
        "use strict";
        if (value_str || value_str === "") {
            $("#q_analysis").val(value_str);
        }
        return window.trim($("#q_analysis").val());
    },
    "sub_answer": function (value_str) {
        "use strict";
        if (value_str || value_str === "") {
            $("#q_answer option[value=" + value_str + "]")[0].selected = true;
        }
        var q_answer = $("#q_answer").val();
        return q_answer instanceof Array ? q_answer.join("") : q_answer;
    }
};
window.sync = {
    "hat_data_html": function () {
        "use strict";
        var question_key = window.question_key,
            question_data = window.format.s2c(window.storage(window.question_key),
                                              window.format.question)[0],
            hat_id = question_data.hat_id,
            hat_key,
            hat_data;
        if (hat_id) {
            hat_key = window.hat_list_key + hat_id + "/";
            hat_data = window.format.s2c(window.storage(hat_key),
                                              window.format.hat)[0];
            window.view.hat_id(hat_data.id);
            window.view.hat_body(hat_data.hat_body);
            window.view.hat_image_id(hat_data.hat_image_id);
        }
    },
    "sublist_data_html": function () {
        "use strict";
        var sub_data_list = window.format.s2c(window.storage(window.sub_key),
                                              window.format.sub),
            sub_data,
            index,
            length = sub_data_list.length,
            sub_id,
            sub_tip,
            optionList = [];
        for (index = 0; index < length; index = index + 1) {
            sub_data = sub_data_list[index];
            sub_id = sub_data.id;
            sub_tip = sub_data.tip;
            optionList.push('<option id="');
            optionList.push("sub_" + sub_id);
            optionList.push('" value="');
            optionList.push(sub_id);
            optionList.push('">');
            optionList.push(sub_id  + "-" + sub_tip + ",");
            optionList.push('</option>');
        }
        $("#sub_list_select").html("");
        $(optionList.join("")).appendTo("#sub_list_select");
    },
    "sub_item_html": function () {
        "use strict";
        var sub_id = window.view.sub_list(),
            sub_list_data = window.format.s2c(window.storage(window.sub_key),
                                              window.format.sub),
            sub_data = null,
            index,
            length = sub_list_data.length,
            item;
        for (index = 0; index < length; index = index + 1) {
            item = sub_list_data[index];
            if (item.id === sub_id) {
                sub_data = item;
                break;
            }
        }
        if (sub_data) {
            window.view.sub_id(sub_data.id);
            window.view.sub_body(sub_data.body);
            //image
            if (sub_data.image_id) {
                window.view.sub_image_id(sub_data.image_id);
            }
            window.view.sub_options(sub_data.options || "");
            window.view.sub_options_count(sub_data.options_count || 4);
            window.view.sub_analysis(sub_data.analysis);
            window.view.sub_answer(sub_data.answer);
        }
    },
    "sub_empty_html": function () {
        "use strict";
        window.view.sub_id("");
        window.view.sub_body("");
        window.listener.hat_image_upload_again();
        window.view.sub_options("");
        //window.view.sub_options_count();
        window.view.sub_analysis("");
        //window.view.sub_answer();
    }
};
window.init = {
    "global_var": function () {
        "use strict";
        var pathname = location.pathname,
            update_reg = new RegExp('^/manager/question/(' +
                                    window.category_list.join("|") +
                                    ')/([0-9]+)/sub/$'),
            reg_result_list = update_reg.exec(pathname);
        if (reg_result_list) {
            //update question
            window.is_valid = true;
            window.question_id = parseInt(reg_result_list[2], 10);
            window.question_type = reg_result_list[1];
            window.question_key = "/question/{id}/".format({id: window.question_id});
            window.sub_key = "/question/{id}/sub/".format({id: window.question_id});
            window.hat_list_key = "/question/{id}/hat/".format({id: window.question_id});
            window.zTree = null;
        } else {
            throw new Error("网页错误");
        }
    },
    "url_varify": function () {
        "use strict";
        if (window.is_valid) {
            var question_key = window.question_key,
                question_data = window.format.s2c(window.storage(question_key),
                                                  window.format.question)[0],
                question_type = window.question_type,
                varify_type = window.category_list.getNameByNum(question_data.category_num),
                url = "/manager/question/{type}/{id}/sub/".format({
                    type: varify_type,
                    id: window.question_id
                });
            if (varify_type !== question_type) {
                window.location.assign(url);
            }
        }
    },
    "hat_html": function () {
        "use strict";
        if (window.is_valid) {
            window.sync.hat_data_html();
            if (window.question_type !== "B1") {
                $("#hat_detail_title").html("情景：");
            }
        }
    },
    "sub_list_html": function () {
        "use strict";
        if (window.is_valid) {
            window.sync.sublist_data_html();
        }
    },
    "addEventListener": function () {
        "use strict";
        $("#upload_file").click(window.listener.image_upload);
        $("#upload_file_change").click(window.listener.image_upload_again);
        $("#hat_upload_file").click(window.listener.hat_image_upload);
        $("#hat_upload_file_change").click(window.listener.hat_image_upload_again);
        $("#add_sub").click(window.listener.add_sub_prepare);
        $("#delete_sub").click(window.listener.delete_sub_from_list);
        $("#edit_sub").click(window.listener.edit_sub_prepare);
        $("#create_sub").click(function () {
            var is_create = window.view.sub_id() === 0;
            if (is_create) {
                window.listener.create_sub();
            } else {
                window.listener.update_sub();
            }
        });
        $("#cancel_sub").click(window.listener.cancel_sub_detail);
        $("#create_hat").click(function () {
            var is_create = window.view.hat_id() === 0;
            if (is_create) {
                window.listener.create_hat();
            } else {
                window.listener.update_hat();
            }
        });
        window.hideLoading();
    }
};
window.init_func_list = ["global_var",
                         "url_varify",
                         "hat_html",
                         "sub_list_html",
                         "addEventListener"];

window.listener = {
    "image_upload": function () {
        "use strict";
        if ($("#upload_file_input").val()) {
            $("#upload_loading").show();
            $.ajaxFileUpload({
                url: '/link/upload/',
                secureuri: false,
                fileElementId: 'upload_file_input',
                dataType: 'json',
                data: {
                    name: $("#file_description").val()
                },
                async: false,
                success: function (result, status) {
                    var image_id = result.id;
                    window.view.sub_image_id(image_id);
                }
            });
        }
    },
    "image_upload_again": function () {
        "use strict";
        $("#upload_control").show();
        $("#upload_result").hide();
        $("#upload_result a").attr("href", "")
            .attr("name", "")
            .html("");
    },
    "hat_image_upload": function () {
        "use strict";
        if ($("#hat_upload_file_input").val()) {
            $("#hat_upload_loading").show();
            $.ajaxFileUpload({
                url: '/link/upload/',
                secureuri: false,
                fileElementId: 'hat_upload_file_input',
                dataType: 'json',
                data: {
                    name: $("#hat_file_description").val()
                },
                async: false,
                success: function (result, status) {
                    var image_id = result.id;
                    window.view.hat_image_id(image_id);
                }
            });
        }
    },
    "hat_image_upload_again": function () {
        "use strict";
        $("#hat_upload_control").show();
        $("#hat_upload_result").hide();
        $("#hat_upload_result a").attr("href", "")
            .attr("name", "")
            .html("");
    },
    "hat_B1_options_show": function () {
        "use strict";
        if (window.question_type !== "B1") {
            $(".A3_A4").show();
        } else {
            $(".A3_A4").hide();
        }
    },
    "add_sub_prepare": function () {
        "use strict";
        window.loading();
        window.sync.sub_empty_html();
        $(".sub_detail").show("normal");
        window.listener.hat_B1_options_show();
        window.hideLoading();
    },
    "edit_sub_prepare": function () {
        "use strict";
        window.loading();
        window.sync.sub_item_html();
        $(".sub_detail").show("normal");
        window.listener.hat_B1_options_show();
        window.hideLoading();
    },
    "cancel_sub_detail": function () {
        "use strict";
        $(".sub_detail").hide("normal");
        window.sync.sub_empty_html();
    },
    "create_sub": function () {
        "use strict";
        window.loading();
        var sub_key = window.sub_key,
            sub_data = fetchSub();
        $.ajax({
            url: sub_key,
            type: "POST",
            data: JSON.stringify(sub_data),
            dataType: "json",
            async: true,
            success: function (result, status) {
                $(".sub_detail").hide("normal");
                var saved_data = window.storage(sub_key);
                window.storage(sub_key, saved_data.concat(result.data));
                window.sync.sublist_data_html();
                window.sync.sub_empty_html();
                window.hideLoading();
            }
        });
    },
    "update_sub": function () {
        "use strict";
        window.loading();
        var sub_key = window.sub_key,
            sub_id =  window.view.sub_id(),
            js_data = fetchSub(),
            server_data = window.storage(window.sub_key),
            transData = window.getChangedValue(js_data, server_data, window.format.sub);
        if (transData === false) {
            window.hideLoading();
            return;
        }
        $.ajax({
            url: sub_key +  sub_id + "/",
            type: "PUT",
            data: JSON.stringify(transData),
            dataType: "json",
            async: true,
            success: function (result, status) {
                var saved_data_list = window.format.s2c(window.storage(sub_key),
                                                   window.format.sub),
                    new_data = window.format.s2c(result.data,
                                                 window.format.sub)[0],
                    id_value = sub_id,
                    index,
                    length = saved_data_list.length,
                    item;
                for (index = 0; index < length; index = index + 1) {
                    item = saved_data_list[index];
                    if (item.id === id_value) {
                        saved_data_list.splice(index, 1, new_data);
                        break;
                    }
                }
                window.storage(sub_key, window.format.c2s(saved_data_list,
                                                                 window.format.sub));
                window.sync.sublist_data_html();
                window.view.sub_list(id_value);
                window.sync.sub_empty_html();
                $(".sub_detail").hide("normal");
                window.hideLoading();
            }
        });
    },
    "delete_sub_from_list": function () {
        "use strict";
        window.loading();
        var delete_sub_id = window.view.sub_list(),
            sub_key = window.sub_key;
        $.ajax({
            url: sub_key + delete_sub_id + "/",
            type: "DELETE",
            dataType: "json",
            async: true,
            success: function (result, status) {
                var saved_sub_list = window.format.s2c(window.storage(window.sub_key),
                                                       window.format.sub),
                    index,
                    length = saved_sub_list.length,
                    sub_item;
                for (index = 0; index < length; index = index + 1) {
                    sub_item = saved_sub_list[index];
                    if (sub_item.id === delete_sub_id) {
                        saved_sub_list.splice(index, 1);
                        break;
                    }
                }
                window.storage(sub_key, window.format.c2s(saved_sub_list,
                                                          window.format.sub));
                window.sync.sublist_data_html();
                window.hideLoading();
            }
        });
        
    },
    "create_hat": function () {
        "use strict";
        window.loading();
        var hat_list_key = window.hat_list_key,
            hat_data = fetchHat();
        $.ajax({
            url: hat_list_key,
            type: "POST",
            data: JSON.stringify(hat_data),
            dataType: "json",
            async: true,
            success: function (result, status) {
                var hat_id = window.format.s2c(result.data,
                                               window.format.hat)[0].id,
                    hat_key = window.hat_list_key + hat_id + "/";
                window.storage(hat_key, result.data);
                window.storageRemove(window.question_key);
                window.sync.hat_data_html();
                window.hideLoading();
            }
        });
    },
    "update_hat": function () {
        "use strict";
        window.loading();
        var hat_id =  window.view.hat_id(),
            hat_key = window.hat_list_key +  hat_id + "/",
            js_data = fetchHat(),
            server_data = window.storage(hat_key),
            transData = window.getChangedValue(js_data, server_data, window.format.hat);
        if (transData === false) {
            window.hideLoading();
            return;
        }
        $.ajax({
            url: hat_key,
            type: "PUT",
            data: JSON.stringify(transData),
            dataType: "json",
            async: true,
            success: function (result, status) {
                window.storage(hat_key, result.data);
                window.sync.hat_data_html();
                window.hideLoading();
            }
        });
        
    }
};
